import Vue from 'vue'
/* api */
import { getAsyncRoleViewInitData } from '@src/api/InitDataApi'
/* view */
import RoleView from '@src/modules/account/role/index.tsx'
import { Loading } from 'element-ui'
/* util */
import qs from 'qs'
import platform from '@src/platform'
import { isNotArray } from '@src/util/type'
/* store */
import store from '@src/modules/account/role/store'
import { useStoreInitData } from '@src/modules/account/role/store/hooks'

const componentItem = (initData) => {
  return {
    provide: {
      initData: Object.freeze(initData)
    },
    render(h) {
      return h(RoleView);
    }
  }
}

Vue.component('async-component', function(resolve) {
  
  // 需要加loading 打开此注释
  // const instance = Loading.service({ fullscreen: true });
  
  let query = qs.parse(window.location.search.substr(1));
  const params = Object.assign({}, query, {})
  
  getAsyncRoleViewInitData(params).then(result => {
    let initJSON = ''
    try {
      initJSON = JSON.parse((result && result.data && result.data.initJson))
    } catch (error) {
      console.error('initJSON 解析失败')
    }
    
    const initData = initJSON || {}
    const title = (result && result.data && result.data.title) || ''
    const isSuccess = result.succ || result.success
    
    if (!isSuccess) {
      window.location.href = '/500'
      return 
    }
    
    try {
      window._init = JSON.stringify(initData)
    } catch (error) {
      console.error('initData 赋值失败')
    }
    
    // 需要加loading 打开此注释
    // instance.close();
    
    if (window.frameElement) {
      const currentTabId = window.frameElement.dataset.id;
      platform.setTabTitle({
        id: currentTabId,
        title
      })
    }
    
    const { setInitData } = useStoreInitData()
    const rolesJson = initData?.rolesJson || []
    
    let newInitData = {
      ...initData,
      rolesJson: rolesJson.map(role => {
        
        if (isNotArray(role?.children)) {
          role.children = []
        }
        
        return role
        
      })
    }
    
    
    setInitData(newInitData)
    
    resolve(componentItem(newInitData))
    
  }).catch(error => {
    console.error(error)
    window.location.href = '/500'
  })
  
})

let app = {
  store,
  render(h) {
    return <async-component />
  }
}

export default app
